package com.rds.benchmark.connector;

import com.rds.benchmark.config.ArgvsConfig;

import java.util.concurrent.CyclicBarrier;

public class Connector {

    public volatile static JedisConnector connector;
    public volatile static CyclicBarrier startBarrier;

    public static JedisConnector getConnector() throws Exception {

        //初始化Barrier
        startBarrier = new CyclicBarrier(ArgvsConfig.threads + 1);

        // 初始化客户端连接
        // 根据不同的客户端
        // 使用不同的连接模式
        // 创建不同的客户端
        if ("jedis".equalsIgnoreCase(ArgvsConfig.clientType)) {
            if ("single".equals(ArgvsConfig.mode)) {
                connector = new SingleJedisConnector();
            } else if ("sentinel".equals(ArgvsConfig.mode)) {
                connector = new SentinelJedisConnector();
            } else if ("cluster".equals(ArgvsConfig.mode)) {
                connector = new ClusterJedisConnector();
            } else {
                throw new Exception("Connection mode error! allowed values: single,sentinel,cluster. " + " mode=" + ArgvsConfig.mode);
            }
        } else if ("redisson".equalsIgnoreCase(ArgvsConfig.clientType)) {
            connector = new RedissonConnector();
        } else if ("lettuce".equalsIgnoreCase(ArgvsConfig.clientType)) {
            if ("single".equals(ArgvsConfig.mode)) {
                connector = new SingleLettuceConnector();
            } else if ("sentinel".equals(ArgvsConfig.mode)) {
                connector = new SentinelLettuceConnector();
            } else if ("cluster".equals(ArgvsConfig.mode)) {
                connector = new ClusterLettuceConnector();
            } else {
                throw new Exception("Connection mode error! allowed values: single,sentinel,cluster. " + " mode=" + ArgvsConfig.mode);
            }
        }

        if (!connector.test()) {
            throw new Exception("Connection test failed! for connector: " + connector);
        }

        return connector;
    }
}
